"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 备节点备份过程中主节点被停掉
Create At   : 2020/11/13
@zou_jialiang0505328126
Description :
    1.备节点备份数据库
    2.备份的过程中停止主节点
    3.使用备份文件恢复数据库
    4.启动数据库
    5.对备库进行build
    6.查询数据是否与备份时一致
Expect      :
    1.备节点备份成功
    2.停止主节点成功
    3.恢复成功
    4.启动数据库成功或出现因为备机为Need repair状态的失败
    5.重建成功
    6.主备数据一致
History     :
    Modified by @peilinqian 2021/2/3: 修改备份路径，解决因原路径为home路径导致备份磁盘不足情况
    Modified by @wan005 2021/1/15: 修改gs_basebackup断言，增加断言信息
"""

import os
import unittest
import time
from yat.test import macro
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class Basebackup(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '----Opengauss_Reliability_Tools_Basebackup_Case003.py 开始执行----')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta2_dbuser = Node(node='Standby2DbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.constant = Constant()
        self.common = Common('PrimaryRoot')
        self.parent_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.backup_path = os.path.join(self.parent_path, 'base_backup')

    def test_basebackup(self):
        self.log.info('----创建备份路径----')
        shell_cmd = f'rm -rf {self.backup_path}; mkdir {self.backup_path}'
        self.log.info(shell_cmd)
        result = self.sta1_dbuser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('----启动线程开始备份----')
        basebackup_thread = ComThread(self.sta_1_sh.execu_gs_basebackup,
                                      args=(self.backup_path,
                                            self.sta1_dbuser.db_host,
                                            self.sta1_dbuser.db_port,))
        basebackup_thread.setDaemon(True)
        basebackup_thread.start()

        self.log.info('----停止主节点----')
        result = self.pri_sh.stopDbInstance()
        self.assertIn(self.constant.GS_CTL_STOP_SUCCESS_MSG, result)

        self.log.info('----检查备份结果----')
        basebackup_thread.join(60 * 60)
        result = basebackup_thread.get_result()
        self.assertNotIn(self.constant.SQL_WRONG_MSG[1], result)
        self.assertNotIn('error', result)
        self.assertIn(self.constant.BASEBACKUP_SUCCESS_MSG, result)
        result = self.sta1_dbuser.sh(
            f'ls -l {self.backup_path} | grep "^-" | wc -l').result()
        self.log.info(result)
        self.assertLess(0, int(result))

        self.log.info('----使用备份文件恢复数据库----')
        result = self.pri_sh.stopDbCluster()
        self.assertTrue(result)
        shell_cmd = f'rm -rf  {macro.DB_INSTANCE_PATH}/* ;' \
            f'cp -R {self.backup_path}/* {macro.DB_INSTANCE_PATH}'
        self.log.info(shell_cmd)
        result = self.sta1_dbuser.sh(shell_cmd).result()
        self.log.info(result)
        time.sleep(2)

        self.log.info('----启动数据库成功或出现因为备机为Need repair状态的失败----')
        result = self.pri_sh.startDbCluster('get_detail')
        self.log.info(result)
        result = ('Degraded' in result) or \
                 (self.constant.START_SUCCESS_MSG in result)
        self.assertTrue(result)
        time.sleep(2)

        self.log.info('----检查备机是否需要重建----')
        result = self.pri_sh.check_whether_need_build()
        success_msg = self.constant.BUILD_SUCCESS_MSG
        if result:
            result = self.sta_1_sh.executeGsctl('build',
                                                success_msg,
                                                '-b full')
            self.assertTrue(result)

        self.log.info('----检查主备是否同步----')
        result = self.sta_1_sh.check_data_consistency()
        self.assertTrue(result)
        result = self.sta_2_sh.check_data_consistency()
        self.assertTrue(result)

        self.log.info('----检查数据一致性----')
        nodes_tuple = (self.pri_dbuser, self.sta1_dbuser, self.sta2_dbuser)
        flag = self.common.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)

        table_dict = self.common.format_sql_result(
            self.pri_sh.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.common.check_data_sample_by_all(select_sql,
                                                        *nodes_tuple)
            self.assertTrue(flag)

    def tearDown(self):
        self.log.info('----环境清理----')
        self.log.info('----删除备份文件----')
        shell_cmd = f'rm -rf {self.backup_path}'
        result = self.sta1_dbuser.sh(shell_cmd).result()
        self.log.info(result)
        self.log.info(
            '----Opengauss_Reliability_Tools_Basebackup_Case003.py 执行结束----')
